fun copyAddress(address: Address): Address {
val result = Address()
result.name = address.name
result.street = address.street
// ...
return result
}
var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]
- Backing fields
需要注意的是,在Kotlin內field不能直接被宣告
在屬性需要Backing fields時,Kotlin會自動提供
var counter = 0
set(value) {
if (value >= 0)
field = value
}
- Backing properties
隱含的backing field若在使用上不符合的話,可以透過Backing properties達到
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null) {
_table = HashMap()
}
return _table ?: throw AssertionError("Set to null by another thread")
}